/**
 * v-debounce
 * 防抖指令
 * Geeker + https://juejin.cn/post/7107477387578703885
 * v-debounce="{fn, event: 'click', delay}"
 */
import type { Directive, DirectiveBinding } from "vue";
interface ElType extends HTMLElement {
	handler: () => any;
	timer: any;
}
const debounce: Directive = {
	mounted(el: ElType, binding: DirectiveBinding) {
		// 至少需要回调函数以及监听事件类型
		if (typeof binding.value.fn !== 'function' || !binding.value.event) return;
		let delay = 200; // 默认延迟时间
		el.timer = null;
		el.handler = function () {
			if (el.timer) {
				clearInterval(el.timer);
				el.timer = null;
			}
			el.timer = setTimeout(() => {
				binding.value.fn.apply(this, arguments)
				el.timer = null;
			}, binding.value.delay || delay);
		};
		el.addEventListener(binding.value.event, el.handler);
	},
	beforeUnmount(el: ElType, binding: DirectiveBinding) {
		if (el.timer) {
			clearTimeout(el.timer);
			el.timer = null;
		}
		el.removeEventListener(binding.value.event, el.handler);
	}
};

export default debounce;
